// src/snake.c

#include <stdio.h>
#include "snake.h"
#include "utils.h"

void initSnake(Snake* snake) {
    snake->length = 3;
    snake->dir = RIGHT;
    snake->body[0].x = GAME_WIDTH / 2;
    snake->body[0].y = GAME_HEIGHT / 2;
    snake->body[1].x = GAME_WIDTH / 2 - 1;
    snake->body[1].y = GAME_HEIGHT / 2;
    snake->body[2].x = GAME_WIDTH / 2 - 2;
    snake->body[2].y = GAME_HEIGHT / 2;
}

void moveSnake(Snake* snake) {
    for (int i = snake->length - 1; i > 0; i--) {
        snake->body[i] = snake->body[i - 1];
    }

    switch (snake->dir) {
    case UP:
        if (snake->body[0].y > 1) {   // 确保蛇不会撞到上边界
            snake->body[0].y--;
        }
        break;
    case DOWN:
        if (snake->body[0].y < GAME_HEIGHT - 2) {  // 确保蛇不会撞到下边界
            snake->body[0].y++;
        }
        break;
    case LEFT:
        if (snake->body[0].x > 1) {   // 确保蛇不会撞到左边界
            snake->body[0].x--;
        }
        break;
    case RIGHT:
        if (snake->body[0].x < GAME_WIDTH - 2) {  // 确保蛇不会撞到右边界
            snake->body[0].x++;
        }
        break;
    }
}

int checkCollision(Snake* snake) {

    // 检查蛇是否撞到了墙壁
//    printf("%d, %d\n", snake->body[0].x, snake->body[0].y);
    if (snake->body[0].x == 0 || snake->body[0].x == GAME_WIDTH - 1 ||
        snake->body[0].y == 0 || snake->body[0].y == GAME_HEIGHT) {
        return 1;
    }

    // 检查自身碰撞
    for (int i = 1; i < snake->length; i++) {
        if (snake->body[0].x == snake->body[i].x && snake->body[0].y == snake->body[i].y) {
            return 1;
        }
    }
    return 0;
}
